<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :title="ruleForm.id == 0 ? '新增床位' : '编辑床位'"
      width="500"
      :before-close="handleClose"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 300px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="房间号:" prop="houseName">
            {{ ruleForm.houseName }}
          </el-form-item>
          <el-form-item label="床位号:" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <el-form-item label="床位月价格:" prop="price">
            <el-input v-model="ruleForm.price" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { bedAddParams } from "@/api/config/bed/type";
import { bedAdd, bedUpdate } from "@/api/config/bed/bed";

const dialogVisible = ref(true);

const ruleForm = reactive<bedAddParams>({
  id: 0,
  houseId: undefined,
  name: "",
  price: "",
  state: 0,
});

// 父组件传过来的数据
const props = withDefaults(defineProps<{ listParams: bedAddParams }>(), {
  listParams: () => ({
    id: 0,
    name: "",
    houseId: 0,
    price: "",
    state: 0,
    houseName: "",
  }),
});

// 添加
const submitForm = async () => {
  let res = await bedAdd(ruleForm);
  // console.log('添加', res);
  ElMessage.success("添加成功");
  emit("close");
};

// 修改
const upData = async () => {
  let res = await bedUpdate(ruleForm);
  // console.log('修改', res);
  ElMessage.success("修改成功");
  emit("close");
};
const submit = async () => {
  await ruleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // submitForm()
      ruleForm.id === 0 ? await submitForm() : await upData();
    }
  });
};

// 表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<bedAddParams>>({
  name: [{ required: true, message: "请输入床位号", trigger: "blur" }],
  price: [{ required: true, message: "请输入床位月价格", trigger: "blur" }],
});

const emit = defineEmits(["close"]);
const handleClose = () => {
  emit("close");
};

onMounted(() => {
  Object.assign(ruleForm, props.listParams);
  console.log(ruleForm.name);
});
</script>

<style scoped></style>
